package com.example.nfcschool;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.example.nfcschool.JoinActivity.JoinJsp;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SModifyActivity extends Activity implements OnClickListener{

	String telno="";
	
	EditText irum_et;
	EditText grade_et;
	EditText pw_et;
	EditText birth_et;
	EditText adds_et;
	EditText sno_et;
	
	SmemberVO d;
	//SmemberVO befored;
	SmemberVO premem;
	TextView go;
	boolean cheeting = true;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_smodify);
		// ActionBar제거한다.
		ActionBar actionBar = getActionBar();
        actionBar.hide();
		
		irum_et = (EditText)findViewById(R.id.irum_edit);
		grade_et = (EditText)findViewById(R.id.grade_edit);
		pw_et = (EditText)findViewById(R.id.pw_edit);
		birth_et = (EditText)findViewById(R.id.birth_edit);
		adds_et = (EditText)findViewById(R.id.adds_edits);
		sno_et = (EditText)findViewById(R.id.sno_edit);
		
		go = (TextView)findViewById(R.id.go_textbtn);
		go.setOnClickListener(this);
		
		Intent i = getIntent();
		telno = i.getStringExtra("tel");
//		Toast.makeText(this, "telno:"+telno, 2000).show();
		
		
//		SDBHelper db = new SDBHelper(this, "1myDB", null, 1);
//		befored = db.select(telno);
		
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		new SelectOneJsp().execute();
		
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		Intent intent = null;
        switch(id){
        case R.id.LOGOUT :
        	FileOutputStream fos = null;
    		try{
    			fos = openFileOutput("auto" , Activity.MODE_PRIVATE);
    			String data = "0";         
    			fos.write(data.getBytes());
    			fos.close();
//    			Toast.makeText(this, "파일이 저장되었습니다.", Toast.LENGTH_SHORT).show();
    		}catch(Exception ex){
    			Log.e("파일 save 에러",ex.toString());
    		}
        	finish();
        	intent = new Intent(this, MainActivity.class);
        	startActivity(intent);
        	break;
        }
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		d = new SmemberVO();
		d.setIrum(irum_et.getText().toString());
		d.setGrade(grade_et.getText().toString());
		d.setPw(Integer.parseInt(pw_et.getText().toString()));
		d.setBirth(birth_et.getText().toString());
		d.setAdds(adds_et.getText().toString());
		d.setTel(telno);
		d.setPicture(premem.getPicture());
		d.setSno(sno_et.getText().toString());
		d.setTeach(premem.getTeach());
//		
//		SDBHelper db = new SDBHelper(this, "1myDB", null, 1);
//		if(db.update(d)){
//			Toast.makeText(this, "수정완료", Toast.LENGTH_SHORT).show();
		new ModiJsp().execute();	
		Intent intent = new Intent(this, SViewActivity.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
		intent.putExtra("tel", telno);
		startActivity(intent);
		cheeting = false;
			
//		}else{
//			Toast.makeText(this, "수정 실패", Toast.LENGTH_SHORT).show();
//		}
	}

	// Font_Join
	protected void onStart() {
		Typeface typeFace = Typeface.createFromAsset(getAssets(), "white.ttf");

		TextView tv1 = (TextView) findViewById(R.id.textView1);
		TextView tv2 = (TextView) findViewById(R.id.textView2);
		TextView tv3 = (TextView) findViewById(R.id.textView3);
		TextView tv4 = (TextView) findViewById(R.id.textView4);
		TextView tv5 = (TextView) findViewById(R.id.textView5);
		TextView tv6 = (TextView) findViewById(R.id.textView6);
		TextView tv7 = (TextView) findViewById(R.id.go_textbtn);

		tv1.setTypeface(typeFace);
		tv2.setTypeface(typeFace);
		tv3.setTypeface(typeFace);
		tv4.setTypeface(typeFace);
		tv5.setTypeface(typeFace);
		tv6.setTypeface(typeFace);
		tv7.setTypeface(typeFace);

		super.onStart();
	}
	
	// ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡWebDB
	public class ModiJsp extends AsyncTask<Void, String, Void> {
		@Override
		protected Void doInBackground(Void... param) {
			
			try {
				HttpClient client = new DefaultHttpClient();
				String postURL = "http://192.168.0.7:8888/AndroidCheck/ModiDB.jsp";
				HttpPost post = new HttpPost(postURL);

				ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
				
				params.add(new BasicNameValuePair("tel", telno));
				params.add(new BasicNameValuePair("irum", d.getIrum()));
				params.add(new BasicNameValuePair("grade", d.getGrade()));
				params.add(new BasicNameValuePair("pw", d.getPw()+""));
				params.add(new BasicNameValuePair("birth", d.getBirth()));
				params.add(new BasicNameValuePair("adds", d.getAdds()));
				params.add(new BasicNameValuePair("sno", d.getSno()));
				params.add(new BasicNameValuePair("picture", d.getPicture()));
				
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);
				HttpEntity resEntity = responsePOST.getEntity();

				if (resEntity != null) {
					Log.i("RESPONSE", EntityUtils.toString(resEntity));
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			Log.e("modiend?", "end?");
			super.onPostExecute(result);
		}
	}
	
	
	public class SelectOneJsp extends AsyncTask<Void, String, Void> {
		
		String tag="";
		StringBuilder sb=new StringBuilder();
	
		
		@Override
		protected Void doInBackground(Void... param) {
			
			try {
				
				Log.e("modipre","pre");
				try{
				HttpClient client = new DefaultHttpClient();
				String postURL = "http://192.168.0.7:8888/AndroidCheck/SelectOne.jsp";
				HttpPost post = new HttpPost(postURL);

				ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
				
				params.add(new BasicNameValuePair("tel", telno));
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);
				HttpEntity resEntity = responsePOST.getEntity();
				
				
				if (resEntity != null) {
//					Log.i("RESPONSE", EntityUtils.toString(resEntity));
					sb.append(EntityUtils.toString(resEntity));
				}else{
					Log.d("SModify Entity is","NULL!!!!!!!!!!!!!!!");
				}
//				client.getConnectionManager().shutdown(); //추가된 코드.
				}catch(Exception ex){
					Log.i("preeeee",ex.toString());
					Log.i("tel",sb.toString());
				}
				
				
				
				// 데이터 받기
				XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
	    		factory.setNamespaceAware(true);             
	    		XmlPullParser xpp = factory.newPullParser(); 
	    		xpp.setInput(new StringReader(sb.toString()));   
	    		int eventType = xpp.getEventType();
	    		
	    		
	    		while(eventType != XmlPullParser.END_DOCUMENT){//현재 이벤트 타입이 END_DOCUMENT를 만날때 까지 반복.
	    			
		    		switch(eventType){
	    			case XmlPullParser.START_TAG :  // 이벤트 타입에 START_TAG 라면.
	    				tag = xpp.getName(); // 태그 이름을 추출함.
	    				if(tag.equals("smember")){
	    					premem = new SmemberVO();
	    				}else if(tag.equals("irum")) {
	    					premem.setIrum(xpp.nextText());
	    				}else if(tag.equals("tel")){
	    					premem.setTel(xpp.nextText());
	    				}else if(tag.equals("picture")){
	    					premem.setPicture(xpp.nextText());
	    				}else if(tag.equals("grade")){
	    					premem.setGrade(xpp.nextText());
	    				}else if(tag.equals("pw")){
	    					premem.setPw(1111);
	    				}else if(tag.equals("birth")){
	    					premem.setBirth(xpp.nextText());
	    				}else if(tag.equals("teach")){
	    					premem.setTeach(xpp.nextText());
	    				}else if(tag.equals("adds")){
	    					premem.setAdds(xpp.nextText());
	    				}else if(tag.equals("sno")){
	    					premem.setSno(xpp.nextText());
	    				}
	    			
	    				break;
	    			
	    			}
	    			eventType = xpp.next();
	    		}
				
				
			} catch (Exception e) {
				Log.e("SModify Async Err",e.toString());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			Log.e("smodiend?", "send?");
			Log.e("premem.getTel", premem.getTel());
			
			irum_et.setText(premem.getIrum());
			grade_et.setText(premem.getGrade());
			pw_et.setText(premem.getPw()+"");
			birth_et.setText(premem.getBirth());
			adds_et.setText(premem.getAdds());
			sno_et.setText(premem.getSno());
			
			super.onPostExecute(result);
		}
	}
	@Override
	protected void onStop() {
		if (cheeting) {
			ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
			try {
				Toast.makeText(getApplicationContext(), "Into try/catch",
						Toast.LENGTH_LONG).show();
				Class localClass = connectivityManager.getClass();
				Class[] arrayOfClass = new Class[1];
				arrayOfClass[0] = Boolean.TYPE;
				Method localMethod = localClass.getMethod(
						"setMobileDataEnabled", arrayOfClass);
				ConnectivityManager localConnectivityManager = connectivityManager;
				Object[] arrayOfObject = new Object[1];
				arrayOfObject[0] = Boolean.valueOf(false);
				localMethod.invoke(localConnectivityManager, arrayOfObject);
				WifiManager wifiManager = (WifiManager) getApplicationContext()
						.getSystemService(Context.WIFI_SERVICE);
				wifiManager.setWifiEnabled(false);

			} catch (Exception e) {
				e.printStackTrace();
			}//ddw
			FileOutputStream fos = null;
			Toast.makeText(getApplicationContext(), "네트워크 차단! 열공하세요!", 2000).show();
			fos = null;
			try {
				// 첫 매개변수는 파일명, 두번째 매개변수는 모드
				fos = openFileOutput("networkcheck", Activity.MODE_PRIVATE);

				String check1 = "true";
				fos.write(check1.getBytes());
				fos.close();
				Toast.makeText(getApplicationContext(), "파일이 저장되었습니다.",
						Toast.LENGTH_SHORT).show();
			} catch (Exception ex) {
				Log.e("파일 save 에러", ex.toString());
			}
		}
		super.onPause();
	}
	
}
